/**
 *
 * @description:Generator
 * @author: junyong.hong
 * @createTime: 2018/3/29
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
{
    // genertaor基本定义
    // 与普通的函数不同：* 、 yield
    let tell = function* () {
        yield 'a';
        yield 'b';
        return 'c';
    };

    // 调用tell，执行到第一个yield停止下来
    let k = tell();

    // 执行第一个yield
    // {value: "a", done: false}
    console.log(k.next());

    // 执行第二个yield
    // {value: "b", done: false}
    console.log(k.next());

    // 执行retrun
    // {value: "c", done: true}
    console.log(k.next());

    // {value: undefined, done: true}
    console.log(k.next());
}

{
    // of遍历
    let obj = {

    };
    obj[Symbol.iterator] = function* () {
        yield 1;
        yield 2;
        yield 3;
    };

    for(let value of obj){
        // 1
        // 2
        // 3
        console.log('value',value);
    }
}

{
    let state = function* () {
        while(1){
            yield 'A';
            yield 'b';
            yield 'c';
        }
    }
    let status = state();
    // {value: "A", done: false}
    // {value: "b", done: false}
    // {value: "c", done: false}
    // {value: "A", done: false}
    // {value: "b", done: false}
    console.log(status.next());
    console.log(status.next());
    console.log(status.next());
    console.log(status.next());
    console.log(status.next());
}

{
    // 抽奖
    let draw = function (count) {
        // 具体抽奖逻辑
        console.info(`剩余${count}次`);
    };

    let residue = function* (count) {
        while (count > 0){
            count--;
            yield draw(count);
        }
    };

    // 可以抽奖5次，如果是最后一次，点击无效
    let star = residue(5);
    let btn = document.createElement('button');
    btn.id = 'start';
    btn.textContent = '抽奖';
    document.body.appendChild(btn);
    document.getElementById('start').addEventListener('click',function () {
        star.next();
    },false)
}

{
    // 长轮询（接口请求失败，一直请求）
    let ajax = function* () {
        yield new Promise(function (resolve,reject) {
            // 接口
            setTimeout(function () {
                resolve({code:0})
            },200);
        })

    };

    let pull = function () {
        let genertaor = ajax();
        let step = genertaor.next();
        step.value.then(function (d) {
            if(d.code != 0){
                setTimeout(function () {
                    console.log('wait');
                    pull();
                },1000);
            }else{
                console.log(d);
            }
        })
    };

    pull();
}